import { ajax, toast } from 'nc-lightapp-front';

function handleErrorToast(res, color ='danger') {
    let msg = '未知错误';
    if (res && res.message) {
        msg = res.message;
    }
    toast({ content: msg, color });
}

function request(url, options) {
    return new Promise((resolve, reject) =>
        ajax({
            url,
            data: options.data,
            success: (res = {}) => {
                if (res.success) {
                    resolve(res.data);
                } else {
                    handleErrorToast(res);
                    reject(res);
                }
            },
            error: (res) => {
                handleErrorToast(res, options.color);
                reject(res);
            }
        })
    );
}

export default request;
